﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Evpo.ContactData.ViewModel;
using Evpo.ContactData.Common;
using Evpo.ContactData.UI.GeneralClasses;

namespace Evpo.ContactData.UI
{
    public partial class AddressSelector : System.Web.UI.Page
    {

        #region Handlers

        protected void Page_Init(object sender, EventArgs e)
        {
            ViewModel = new AddressEditViewModel(
                new ModelFactory(),
                (IConnection)Session[SessionStateKeys.Connection]);

            uiAddressList.AddressSelected += uiAddressList_AddressSelected;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                DataBind();
            else
                uiContactInList.DataBind();

        }

        protected void Page_Unload(object sender, EventArgs e)
        {
            uiAddressList.AddressSelected -= uiAddressList_AddressSelected;
        }

        protected void uiAddressList_AddressSelected(object sender, SelectedItemEventArgs e)
        {
            ViewModel.UpdateContact(ContactID, e.ItemID);
            Response.Redirect(UrlHelper.ContactUrl(ContactID, Request.Url).ToString());
        }

        #endregion Handlers

        #region Properties

        protected ContactListItem _contactListItem;

        protected bool AddressNotEmpty
        {
            get
            {
                if(_contactListItem == null)
                    _contactListItem = ViewModel.LoadContactListItem(ContactID);

                return _contactListItem.Contact.AddressID.HasValue;
            }
        }

        protected int? AddressID
        {
            get
            {
                if (_contactListItem == null)
                    _contactListItem = ViewModel.LoadContactListItem(ContactID);

                return _contactListItem.Contact.AddressID;
            }
        }

        protected AddressEditViewModel ViewModel
        {
            get;
            private set;
        }

        protected int ContactID
        {
            get
            {
                string s = Request.Params["ID"];
                if (String.IsNullOrEmpty(s))
                    throw new ApplicationException("Can't find parameter ContactID");
                return Int32.Parse(s);
            }
        }

        protected Uri CreateAddressUrl
        {
            get
            {
                return UrlHelper.UrlWithID("ContactID", ContactID, Request.Url, typeof(AddressEditForm).Name);
            }
        }
        #endregion Properties

    }
}